package com.zHan.common.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: JwtHelper
 * Description: 生成JSON Web令牌的工具类
 * date: 2023/6/25 0025 15:17
 *
 * @author zHan
 */
public class JwtUtil {

    // token过期时间
    private static long tokenExpiration = 365 * 24 * 60 * 60 * 1000;
    // 加密密钥
    private static String tokenSignKey = "zHan";

    /**
     * 根据用户id和用户名称生成token字符串
     *
     * @param userId
     * @param username
     * @return
     */
    public static String createToken(String userId, String username) {
        String token = Jwts.builder()
                .setSubject("AUTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("username", username)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    /**
     * 获取token
     *
     * @param token
     * @return
     */
    public static Map<String, String> getToken(String token) {
        try {
            if (StringUtils.isEmpty(token)) return null;

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            String userId = (String) claims.get("userId");
            String username = (String) claims.get("username");
            // 封装成map集合
            Map<String, String> map = new HashMap<>();
            map.put("userId", userId);
            map.put("username", username);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void removeToken(String token) {
        //jwttoken无需删除，客户端扔掉即可。
    }
}
